package net.organizer.ui.actionhandler;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.Org;
import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgDeleteActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgDeleteActionHandler.class.getName());

	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Domain domain = new Domain();
		domain.setName("domain1");
		Objectify ofy = ObjectifyService.beginTransaction();
		try {
			if (req.getParameterValues("tree") != null) {
				Set<Long> paramIds = new HashSet<Long>();
				if (req.getParameterValues("tree") != null) {
					for (String value : req.getParameterValues("tree")) {
						logger.finer(String.format("...parameter value: %s", value));
						Long id = Long.parseLong(value);
						paramIds.add(id);
					}
				}
				logger.info(String.format("after load of http params... ids.size(): %d", paramIds.size()));
				List<Org> orgs = ofy.query(Org.class).ancestor(Domain.getKey("domain1")).order("name").list();
				
				Set<Long> ids = new HashSet<Long>();
				for(Long paramId : paramIds){
					this.loadChildren(orgs, paramId, ids);
				}

				
				List<Key<Org>> orgKeys = new LinkedList<Key<Org>>();
				for (Long id : ids) {
					orgKeys.add(Org.getKey(domain, id));
				}
				logger.info(String.format("will delete %d orgs", orgKeys.size()));
				ofy.delete(orgKeys);
				ofy.getTxn().commit();
			} else {
				logger.info("attempt to delete, but no ids were supplied");
			}
		} finally {
			if (ofy.getTxn().isActive()) {
				ofy.getTxn().rollback();
			}
		}
		
	}
	public void loadChildren(List<Org> orgs, Long id, Set<Long> ids){
		ids.add(id);
		for(Org org : orgs){
			if(org.getParentOrgKey() != null){
				//logger.info(String.format("parent id: %d ", org.getParentOrgKey().getId()));
				if(org.getParentOrgKey().getId() == id){
					logger.info(String.format("have child... parentId: %d, childId: %d", id, org.getId()));
					loadChildren(orgs, org.getId(), ids);
				}
			}
		}
	}
}
